#!/usr/bin/env python
# encoding: utf-8
"""
steamfeed.py

Created by Mike Thorpe on 2009-07-24.
Copyright (c) 2009 Mike Thorpe. All rights reserved.
"""

import sys
import os
import time

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.ext import db

from xml.dom import minidom
from django.utils import simplejson as json

from models import FeedItem

class UpdateHandler(webapp.RequestHandler):
  def get(self):
    url = self.request.get('feed')
    error_msgs = []
    status_msgs = []
    new_items = 0
    
    if url:
      r = urlfetch.fetch(url)
      
      if r.status_code == 200:
        dom = minidom.parseString(r.content)
        
        # Delete old records
        q = db.GqlQuery("SELECT * FROM FeedItem")
        results = q.fetch(1000)

        while len(results) > 0:
          db.delete(results)
          results = q.fetch(1000, len(results))
        
        
        for item in dom.getElementsByTagName('item'):
          try:
            title = item.getElementsByTagName('title')[0].firstChild.data
            pubDate = item.getElementsByTagName('dc:date')[0].firstChild.data
            
            link = "" # Link can be null, apparently.
            if item.getElementsByTagName('link')[0].firstChild:
              link = item.getElementsByTagName('link')[0].firstChild.data
            
            query = db.GqlQuery("SELECT * FROM FeedItem WHERE title = :1 AND pubDate = :2", title, pubDate)
            if query.count() == 0:
              new_items += 1
              item = FeedItem(
                              title=title,
                              pubDate=pubDate,
                              link=link,
                              feed=url
                              ) 
              item.put()
        
          except IndexError, ValueError: 
            # Exceptions thrown from minidom parser.
            error_msgs.append("Failed Parsing feed XML.")
            
        # end for item
        status_msgs.append("Update Complete")
        
      else: # r.status_code == 200
        error_msgs.append("Failed to grab rss feed.")
        
    self.response.headers["Content-Type"] = "text/plain"
    self.response.out.write( json.JSONEncoder().encode(
                                                        { "new_items": new_items , 
                                                          "status_msgs": status_msgs,
                                                          "error_msgs": error_msgs }
                                                          ))
    


# MAIN WEBAPP
application = webapp.WSGIApplication(
                                     [
                                      ('/steamfeed/update', UpdateHandler),
                                     ],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()